<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model\DepartmentModel;		// 部门
use app\admin\model\DaystatisticModel;		// 日报统计表
use app\admin\model\RecfpstatisticModel;	// 电商扶贫情况汇总列表
use app\admin\model\PubstatisticModel;		// 公共服务体系建设情况列表
use app\admin\model\LogisticstatisticModel;	// 物流配送体系建设情况列表
use app\admin\model\RectrainstatisticModel; // 农村电商培训情况汇总列表
// use app\admin\model\MonthtableModel;	// 月报表
// use app\admin\model\YeartableModel;		// 年报表
// use app\admin\model\CapitaltableModel;	// 资金管理表
// use app\admin\model\WebshoptableModel;	// 网点表
// use app\admin\model\AssettableModel;	// 固定资产表

class Statistics extends Base{

	/**
	 * [构造函数]
	 */
	public function _initialize() {
		parent::_initialize();
		$DepartModel = new DepartmentModel();
		$departs = $DepartModel->getCanSeeDepart(session('id'));
		$departs = $this->arr2tree($departs);
		$depart_opt = $this->getNameByTree($departs);
		$this->assign([
			'DepartOpt' => $depart_opt
		]);
	}

	public function T($format="Y-m",$str="-1 month") {
		return strtotime(date($format,strtotime($str)));
	}

	/**
	 * [交易信息汇总]
	 */
	public function transaction() {
		if($this->request->isPost()){
			# 搜索参数处理
			$param = input('post.');
			$where = [];
			if($param['depart_id'] != ''){
				$DepartModel = new DepartmentModel();
				$departIdArr = $DepartModel->getSonsByPid($param['depart_id']);
				foreach($departIdArr as &$v){
					$v = $v['id'];
				}
				$departIdArr[] = $param['depart_id'];
				$where['depart_id'] = ['in',$departIdArr];
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}else{
				$where['rpt_date'] = ['between',[strtotime('-3 month'),strtotime('-1 month')]];
			}
			# 数据查询
			$data = DB::name('goods_cate')->where('pid','<>',0)->order('pid asc')->order('id asc')->select();
			$DayModel = new DaystatisticModel();
			foreach($data as $k => &$v){
				$v['row_num'] = DB::name('goods_cate')->where('pid',$v['pid'])->count();
				$buyIdArr = DB::name('goods_cate')->where('pid',$v['pid'])->column('commid');
				$selIdArr = DB::name('goods_cate')->where('pid',$v['pid'])->column('commid_2');
				$v['buy'] =
					$DayModel->getStatistics($where,['buy_commid'=>$v['commid']],'buy_money');
				$v['sell'] =
					$DayModel->getStatistics($where,['sell_commid'=>$v['commid_2']],'sell_money');
				$v['buy_sum'] =
					$DayModel->getStatistics($where,['buy_commid'=>['in',$buyIdArr]],'buy_money');
				$v['sell_sum'] =
					$DayModel->getStatistics($where,['sell_commid'=>['in',$selIdArr]],'sell_money');
			}
			return ['code'=>1,'msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'date',
			's_time' => strtotime('-3 month')*1000,
			'e_time' => strtotime('-1 month')*1000
		]);
		return $this->fetch();
	}

	/**
	 * [电商扶贫情况汇总]
	 */
	public function rec_poverty_alleviation() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['depart_id'] != ''){
				$where['depart_id'] = $param['depart_id'];
			}
			if($param['time'] != ''){
				$where['rpt_date'] = $param['time']/1000;
			}else{
				$where['rpt_date'] = strtotime(date("Y-m",time()));
			}
			$statisticModel = new RecfpstatisticModel();
			$data['rows'] = $statisticModel->getListRows($where,$offset,$limit);
			foreach($data['rows'] as &$v){
				$v['help_1'] = DB::name('statistics_recfp')->where([
					'depart_id' => $v['depart_id'],
					'rpt_date' => ['<=',$v['rpt_date']]
				])->sum('help_0');
				$v['help_5'] = DB::name('statistics_recfp')->where([
					'depart_id' => $v['depart_id'],
					'rpt_date' => ['<=',$v['rpt_date']]
				])->sum('help_4');
				$v['help_7'] = DB::name('statistics_recfp')->where([
					'depart_id' => $v['depart_id'],
					'rpt_date' => ['<=',$v['rpt_date']]
				])->sum('help_6');
				$v['help_9'] = DB::name('statistics_recfp')->where([
					'depart_id' => $v['depart_id'],
					'rpt_date' => ['<=',$v['rpt_date']]
				])->sum('help_8');
				$v['train_1'] = DB::name('statistics_recfp')->where([
					'depart_id' => $v['depart_id'],
					'rpt_date' => ['<=',$v['rpt_date']]
				])->sum('train_0');
				$v['train_3'] = DB::name('statistics_recfp')->where([
					'depart_id' => $v['depart_id'],
					'rpt_date' => ['<=',$v['rpt_date']]
				])->sum('train_2');
			}
			$data['total'] = $statisticModel->getCount($where);
			return ['code'=>'1','msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month',
			'seaTime' => strtotime(date("Y-m",time()))*1000
		]);
		return $this->fetch();
	}

	/**
	 * [公共服务体系建设情况汇总]
	 */
	public function pub_service_system_bulid() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['depart_id'] != ''){
				$where['depart_id'] = $param['depart_id'];
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}else{
				$where['rpt_date'] = ['between',[$this->T("Y-m","-3 month"),$this->T()]];
			}
			$statisticModel = new PubstatisticModel();
			$data['rows'] = $statisticModel->getListRows($where,$offset,$limit);
			$data['total'] = $statisticModel->getCount($where);
			return ['code'=>'1','msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month'
		]);
		return $this->fetch();
	}

	/**
	 * [物流配送体系建设情况汇总]
	 */
	public function logistics_system_bulid() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['depart_id'] != ''){
				$where['depart_id'] = $param['depart_id'];
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}else{
				$where['rpt_date'] = ['between',[$this->T("Y-m","-3 month"),$this->T()]];
			}
			$statisticModel = new LogisticstatisticModel();
			$data['rows'] = $statisticModel->getListRows($where,$offset,$limit);
			$data['total'] = $statisticModel->getCount($where);
			return ['code'=>'1','msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month'
		]);
		return $this->fetch();
	}

	/**
	 * [农村电子商务情况汇总]
	 */
	public function rec_business() {
		if($this->request->isPost()){
			$param = input("post.");
			$where = [];
			if($param['depart_id'] != ''){
				$departs = DB::name("department")->where('id',$param['depart_id'])->select();
			}else{
				$DepartModel = new DepartmentModel();
				$departs = $DepartModel->getCanSeeDepart(session('id'));
			}
			if($param['time'] != ''){
				$where['rpt_date'] = $param['time'] / 1000;
			}else{
				$where['rpt_date'] = strtotime(date("Y-m",strtotime("-1 month")));
			}
			$prevTime = strtotime("-1 month",$where['rpt_date']);
			foreach($departs as $d){
				$info = DB::name("statistics_recbusiness")->where([
					'depart_id' => $d['id'],
					'rpt_date' => $where['rpt_date']
				])->find();
				$info_prev = DB::name("statistics_recbusiness")->where([
					'depart_id' => $d['id'],
					'rpt_date' => $prevTime
				])->find();
				$row = [
					'id' => $d['id'],
					'depart_name' => $d['name'],
					'net_sale' => $info['net_sale'],
					'suk' => $info['suk'],
					'total_net_sale' => DB::name("statistics_recbusiness")->where([
						'depart_id' => $d['id'],
					])->sum('net_sale'),
					'total_suk' => DB::name("statistics_recbusiness")->where([
						'depart_id' => $d['id'],
					])->sum('suk')
				];
				if($info_prev['net_sale'] != 0){
					$row['ring_ratio_sale'] = ($info['net_sale'] - $info_prev['net_sale']) / $info_prev['net_sale'] * 100;
				}else{
					$row['ring_ratio_sale'] = 0;
				}
				if($info_prev['suk'] != 0){
					$row['ring_ratio_suk'] = ($info['suk'] - $info_prev['suk']) / $info_prev['suk'] * 100;
				}else{
					$row['ring_ratio_suk'] = 0;
				}
				$row['net_sale'] == "" ? $row['net_sale'] = 0 : $row['net_sale'] = $row['net_sale'];
				$row['suk'] == "" ? $row['suk'] = 0 : $row['suk'] = $row['suk'];
				$data['rows'][] = $row;
			}
			return ['code'=>'1','msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month',
			'seaTime' => strtotime(date("Y-m",strtotime("-1 month")))*1000
		]);
		return $this->fetch();
	}

	/**
	 * [农村电商培训情况汇总]
	 */
	public function rec_train() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['depart_id'] != ''){
				$where['depart_id'] = $param['depart_id'];
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}else{
				$where['rpt_date'] = ['between',[$this->T("Y-m","-3 month"),$this->T()]];
			}
			$statisticModel = new RectrainstatisticModel();
			$data['rows'] = $statisticModel->getListRows($where,$offset,$limit);
			$data['total'] = $statisticModel->getCount($where);
			return ['code'=>'1','msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month'
		]);
		return $this->fetch();
	}

	/**
	 * [资金使用情况汇总]
	 */
	public function capital_use() {
		if($this->request->isPost()){
			$param = input("post.");
			$where = [];
			if($param['depart_id'] != ''){
				$departs = DB::name("department")->where('id',$param['depart_id'])->select();
			}else{
				$DepartModel = new DepartmentModel();
				$departs = $DepartModel->getCanSeeDepart(session('id'));
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}else{
				$where['rpt_date'] = ['between',[$this->T("Y-m","-3 month"),$this->T()]];
			}
			$seaYear['s'] = date("Y",$where['rpt_date'][1][0]);
			$seaYear['e'] = date("Y",$where['rpt_date'][1][1]);

			$data = [];
			foreach($departs as $d){
				$row = [
					'id' => $d['id'],
					'depart_name' => $d['name'],
					'total_money' => DB::name("capital_mgr")->where([
						'depart_id' => $d['id'],
						'year' => ['between',[$seaYear['s'],$seaYear['e']]]
					])->sum('capital'),
					'center_money' => DB::name("statistics_capitaluse")->where([
						'depart_id' => $d['id'],
						'rpt_date' => $where['rpt_date']
					])->sum('center_money'),
					'center_pay' => DB::name("statistics_capitaluse")->where([
						'depart_id' => $d['id'],
						'rpt_date' => $where['rpt_date']
					])->sum('center_pay'),
					'local_money' => DB::name("statistics_capitaluse")->where([
						'depart_id' => $d['id'],
						'rpt_date' => $where['rpt_date']
					])->sum('local_money'),
					'company_pay' => DB::name("statistics_capitaluse")->where([
						'depart_id' => $d['id'],
						'rpt_date' => $where['rpt_date']
					])->sum('company_pay')
				];
				if($row['total_money'] != 0){
					$row['ratio'] = $row['center_pay'] / $row['total_money'] * 100;
				}else{
					$row['ratio'] = '0';
				}
				$row['ratio'] = round($row['ratio'],2);
				$data['rows'][] = $row;
			}
			return ['code'=>'1','msg'=>'表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month',
			's_time' => $this->T("Y-m","-3 month") * 1000,
			'e_time' => $this->T() * 1000
		]);
		return $this->fetch();
	}

	/**
	 * [资金管理情况汇总]
	 */
	public function capital_mgr() {
		if($this->request->isPost()){
			$param = input("post.");
			$where = [];
			if($param['depart_id'] != ''){
				$departs = DB::name("department")->where('id',$param['depart_id'])->select();
			}else{
				$DepartModel = new DepartmentModel();
				$departs = $DepartModel->getCanSeeDepart(session('id'));
			}
			$data = [];
			foreach($departs as $d){
				$row = [
					'id' => $d['id'],
					'depart_name' => $d['name'],
					'company_count' => DB::name('table_capital')->where([
						'depart_id' => $d['id']
					])->count(),
					'project_count' => DB::name('statistics_capitalmgr')->where([
						'depart_id' => $d['id']
					])->count()
				];
				$row['already'] = DB::name('statistics_capitalmgr')->where([
					'depart_id' => $d['id']
				])->sum('already');
				$row['unalready'] = DB::name('statistics_capitalmgr')->where([
					'depart_id' => $d['id']
				])->sum('unalready');
				if($row['already'] + $row['unalready'] != 0) {
					$row['ratio'] = $row['already'] / ($row['already'] + $row['unalready']) * 100;
				}else{
					$row['ratio'] = 0;
				}
				$row['ratio'] = round($row['ratio'],2);
				$data['rows'][] = $row;
			}
			return ['code' => 1,'msg' => '表格加载成功','data'=>$data];
		}
		return $this->fetch();
	}

	/**
	 * [网店信息汇总]
	 */
	public function webshop() {
		if($this->request->isPost()){
			$param = input("post.");
			$where = [];
			if($param['depart_id'] != ''){
				$departs = DB::name("department")->where('id',$param['depart_id'])->select();
			}else{
				$DepartModel = new DepartmentModel();
				$departs = $DepartModel->getCanSeeDepart(session('id'));
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}else{
				$where['rpt_date'] = ['between',[$this->T("Y-m","-3 month"),$this->T()]];
			}
			$data = [];
			foreach($departs as $d){
				$row = [
					'id' => $d['id'],
					'depart_name' => $d['name'],
					'webshop_num' => DB::name('webshop')->where('depart_id',$d['id'])->count(),
				];
				$row['pro_num'] = DB::name('statistics_webshop')->where([
					'depart_id' => $d['id'],
					'rpt_date' => $where['rpt_date']
				])->sum('pro_num');
				$row['sales_amount'] = DB::name('statistics_webshop')->where([
					'depart_id' => $d['id'],
					'rpt_date' => $where['rpt_date']
				])->sum('sales_amount');
				$data['rows'][] = $row;
			}
			return ['code' => 1,'msg' => '表格加载成功','data'=>$data];
		}
		$this->assign([
			'PickerType' => 'month',
			's_time' => $this->T("Y-m","-3 month")*1000,
			'e_time' => $this->T()*1000
		]);
		return $this->fetch();
	}

	/**
	 * [首页统计信息]
	 */
	public function indexPage() {
		// 根据可视权限做
	}
}
